<template>
  <view class="template-classify tn-safe-area-inset-bottom">


      <!-- 顶部自定义导航 -->
      <tn-nav-bar fixed alpha customBack>
      <view slot="back" class='tn-custom-nav-bar__back'
        @click="goBack">
        <text class='icon tn-icon-left'></text>
        <text class='icon tn-icon-home-capsule-fill'></text>
      </view>
    </tn-nav-bar>


    <view
      class="tn-classify__wrap"
      :style="{ paddingTop: vuex_custom_bar_height + 'px' }"
    >
      <!-- 搜索框 -->
      <view
        class="tn-classify__search--wrap tn-flex tn-flex-col-center tn-flex-row-center tn-border-solids-bottom"
      >
        <view
          class="tn-classify__search__box tn-flex tn-flex-col-center tn-flex-row-center tn-bg-gray--light tn-color-gray--dark"
        >
          <view class="tn-classify__search__icon tn-icon-search"></view>
          <input
            class="tn-classify__search__input"
            v-model="searchKeyword"
            placeholder="请输入商品名称"
            @input="handleSearch"
          />
        </view>
      </view>

      <!-- 顶部分类滚动区 -->
      <scroll-view
        class="category-scroll"
        scroll-x
        :scroll-left="categoryScrollLeft"
      >
        <view class="category-list">
          <view
            v-for="(item, index) in tabbar"
            :key="index"
            :id="`category_${index}`"
            class="category-item"
            :class="{ 'category-item--active': currentTabbarIndex === index }"
            @tap="clickClassifyNav(index)"
          >
            {{ item.name }}
          </view>
        </view>
      </scroll-view>

      <!-- 分类列表和内容 -->
      <view class="tn-classify__container tn-bg-gray--light">
        <view
          class="tn-classify__container__wrap tn-flex tn-flex-nowrap tn-flex-row-around tn-bg-white"
        >
          <!-- 左边品牌容器 -->
          <scroll-view
            class="tn-classify__left-box tn-flex-basic-sm"
            :scroll-top="leftScrollViewTop"
            scroll-y
            scroll-with-animation
            :style="{ height: scrollViewHeight + 'px' }"
          >
            <!-- 全部品牌选项 -->
            <view
              class="tn-classify__tabbar__item tn-flex tn-flex-col-center tn-flex-row-center"
              :class="[selectedBrandIds.length === 0 ? 'tn-classify__tabbar__item--active tn-bg-white' : '']"
              @tap.stop="selectAllBrands"
            >
              <view class="tn-classify__tabbar__item__title">全部</view>
            </view>
            
            <view
              v-for="(brand, index) in currentBrands"
              :key="brand.id"
              :id="`brand_${index}`"
              class="tn-classify__tabbar__item tn-flex tn-flex-col-center tn-flex-row-center"
              :class="[selectedBrandIds.includes(brand.id) ? 'tn-classify__tabbar__item--active tn-bg-white' : '']"
              @tap.stop="handleBrandClick(brand.id)"
            >
              <view class="tn-classify__tabbar__item__title">{{ brand.name }}</view>
            </view>
          </scroll-view>

          <!-- 右边商品容器 -->
          <scroll-view
            class="tn-classify__right-box"
            scroll-y
            :scroll-top="rightScrollViewTop"
            :style="{ height: scrollViewHeight + 'px' }"
          >
            <block>
              <view class="tn-classify__content">
                <!-- 商品列表区域 -->
                <div class="goods-list">
                  <div
                    v-for="product in formattedProducts"
                    :key="product.id"
                    class="goods-item"
                    @click="goToDetail(product)"
                  >
                    <!-- 第1行：图片和标题 -->
                    <div class="row-1">
                      <img
                        :src="`${$minApi.imgOrigin}${product.mainImage}`"
                        class="goods-image"
                        @click.stop="previewImage(`${$minApi.imgOrigin}${product.mainImage}`)"
                      />
                      <div class="title-container">
                        <div class="goods-title">{{ product.name }}</div>
                        <div class="goods-spec">{{ product.specification }}</div>
                      </div>
                    </div>
                    <!-- 价格信息区域 -->
                    <div class="price-info-container">
                      <!-- 第2行：单件价格 -->
                      <div class="row-2">
                        <div class="price-row">
                          <span class="quantity-tag">单件</span>
                          <div class="price-content">
                            <span class="price">{{ product.purchasePrice }}</span>
                            <span class="price">{{ product.recoveryPrice }}</span>
                            <span class="price">{{ product.userProfit}}</span>
                          </div>
                        </div>
                      </div>
                      <!-- 第2.1行：两件价格 -->
                      <div class="row-2">
                        <div class="price-row">
                          <span class="quantity-tag">两件</span>
                          <div class="price-content">
                            <span class="price">{{ product.purchasePrice2 }}</span>
                            <span class="price">{{ product.recoveryPrice2 }}</span>
                            <span class="price">{{ product.userProfit2 }}</span>
                          </div>
                        </div>
                      </div>
                      <!-- 第3行：价格说明文字 -->
                      <div class="row-3">
                        <span class="price-desc">{{ priceLabels.price }}</span>
                        <span class="price-desc">{{
                          priceLabels.originalPrice
                        }}</span>
                        <span class="price-desc">{{ priceLabels.profit }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </view>
              <view class="tn-padding-bottom"></view>
            </block>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>



<script>
export default {
  name: "templateShopClassify",

  data() {
    return {
      tabbar: [], // 分类列表
      currentTabbarIndex: 0, // 当前选中的分类索引
      leftScrollViewTop: 0,
      rightScrollViewTop: 0,
      categoryScrollLeft: 0, // 分类横向滚动位置
      currentBrands: [], // 当前分类下的品牌
      selectedBrandIds: [], // 选中的品牌ID
      brandProducts: [], // 当前品牌下的商品
      filteredProducts: [], // 搜索过滤后的商品
      searchKeyword: '', // 搜索关键词
      // 价格说明文字
      priceLabels: {
        price: "采购价",
        originalPrice: "参考行情价",
        profit: "收益",
      },
    };
  },

  // 在created生命周期中获取初始数据
  async created() {
    try {
      await this.fetchCategories();
    } catch (err) {
      console.error("初始化数据失败:", err);
      uni.showToast({
        title: "获取数据失败",
        icon: "none",
      });
    }
  },

  computed: {
    tabbarItemClass() {
      return (index) => {
        if (index === this.currentTabbarIndex) {
          return "tn-classify__tabbar__item--active tn-bg-white";
        } else {
          let clazz = "tn-bg-gray--light";

          if (
            this.currentTabbarIndex > 0 &&
            index === this.currentTabbarIndex - 1
          ) {
            clazz += " tn-classify__tabbar__item--active--prev";
          }

          if (
            this.currentTabbarIndex < this.tabbar.length &&
            index === this.currentTabbarIndex + 1
          ) {
            clazz += " tn-classify__tabbar__item--active--next";
          }

          return clazz;
        }
      };
    },

    // 根据选中的标签筛选商品
    filteredProducts() {
      if (!this.selectedTags.length) return [];

      return this.selectedTags.reduce((acc, tagCode) => {
        return acc.concat(this.productsData[tagCode] || []);
      }, []);
    },

    getTagClass() {
      return (tag) => {
        return {
          "brand-tag--active": this.selectedTags.includes(tag.code),
        };
      };
    },

    isAllSelected() {
      return this.currentBrands.length > 0 && this.selectedBrandIds.length === this.currentBrands.length;
    },

    // 格式化商品数据，添加两件价格的计算
    formattedProducts() {
      const products = this.searchKeyword ? this.filteredProducts : this.brandProducts;
      return products.map(product => {
        // 计算两件价格，保留两位小数
        const purchasePrice2 = (parseFloat(product.purchasePrice) * 2).toFixed(2);
        const recoveryPrice2 = (parseFloat(product.recoveryPrice) * 2).toFixed(2);
        const userProfit2 = (parseFloat(product.userProfit) * 2).toFixed(2);

        return {
          ...product,
          purchasePrice2,
          recoveryPrice2,
          userProfit2
        };
      });
    },
  },

  onReady() {
    this.$nextTick(() => {
      this.getScrollViewInfo();

      this.getTabbarItemRect();

      // 初始化时选中第一个标签
      this.initializeFirstTag();
    });
  },

  methods: {
    // 跳转
    tn(e) {
      uni.navigateTo({
        url: e,
      });
    },

    // 获取scrollView的高度信息
    getScrollViewInfo() {
      // 获取搜索栏的bottom信息，然后用整个屏幕的可用高度减去bottom的值即可获取scrollView的高度(防止双重滚动)

      this._tGetRect(".tn-classify__search--wrap").then((rect) => {
        // 如果获取失败重新获取

        if (!rect) {
          setTimeout(() => {
            this.getScrollViewInfo();
          }, 10);

          return;
        }

        // 获取当前屏幕的可用高度

        const systemInfo = uni.getSystemInfoSync();

        this.scrollViewBasicTop =
          systemInfo.statusBarHeight + rect.bottom + uni.upx2px(10);

        this.scrollViewHeight =
          systemInfo.safeArea.height +
          systemInfo.statusBarHeight -
          rect.bottom -
          uni.upx2px(10);
      });
    },

    // 获取分类菜单每个item的信息
    getTabbarItemRect() {
      let view = uni.createSelectorQuery().in(this);

      for (let i = 0; i < this.tabbar.length; i++) {
        view.select("#tabbar_item_" + i).boundingClientRect();
      }

      view.exec((res) => {
        if (!res.length) {
          setTimeout(() => {
            this.getTabbarItemRect();
          }, 10);

          return;
        }

        // 将每个分类item的相关信息

        res.map((item) => {
          this.tabbarItemInfo.push({
            top: item.top,

            height: item.height,
          });
        });
      });
    },

    // 点击分类导航
    async clickClassifyNav(index) {
      if (this.currentTabbarIndex === index) {
        return;
      }
      this.currentTabbarIndex = index;
      
      // 计算分类滚动位置
      this.calculateCategoryScroll(index);
      
      // 获取当前分类的品牌数据
      const categoryId = this.tabbar[index].id;
      await this.fetchBrandsByCategory(categoryId);
    },

    // 计算分类滚动位置
    calculateCategoryScroll(index) {
      // 获取当前点击的分类元素
      const query = uni.createSelectorQuery().in(this);
      query.select(`#category_${index}`).boundingClientRect();
      query.selectViewport().scrollOffset();
      query.exec((res) => {
        if (res[0]) {
          // 计算需要滚动的距离，使选中项居中
          const windowWidth = uni.getSystemInfoSync().windowWidth;
          const itemWidth = res[0].width;
          const itemLeft = res[0].left;
          const scrollLeft = itemLeft - (windowWidth - itemWidth) / 2;
          this.categoryScrollLeft = scrollLeft;
        }
      });
    },

    // 选择全部品牌
    async selectAllBrands() {
      this.selectedBrandIds = [];
      await this.fetchProductsByBrand([]);
    },

    // 点击品牌
    async handleBrandClick(brandId) {
      // 单选模式
      this.selectedBrandIds = [brandId];
      await this.fetchProductsByBrand(this.selectedBrandIds);
    },

    // 根据分类ID获取品牌列表
    async fetchBrandsByCategory(categoryId) {
      try {
        const res = await this.$minApi.getBrandsByCategory(categoryId);
        if (res.success) {
          this.currentBrands = res.data;
          // 默认不选中任何品牌，显示全部
          this.selectedBrandIds = [];
          await this.fetchProductsByBrand([]);
        }
      } catch (err) {
        console.error("获取品牌列表失败:", err);
        uni.showToast({
          title: "获取品牌列表失败",
          icon: "none",
        });
      }
    },

    // 获取品牌下的商品
    async fetchProductsByBrand(brandIds) {
      try {
        const res = await this.$minApi.getProductsByBrand({
          brandIds: Array.isArray(brandIds) ? brandIds : [brandIds],
          categoryId: this.tabbar[this.currentTabbarIndex].id
        });
        if (res.success) {
          // 对商品列表按收益倒序排序
          const sortedList = res.data.list.sort((a, b) => {
            return parseFloat(b.userProfit) - parseFloat(a.userProfit);
          });
          
          this.brandProducts = sortedList;
          this.searchKeyword = ''; // 重置搜索关键词
          this.filteredProducts = sortedList; // 重置过滤后的商品列表
        }
      } catch (err) {
        console.error("获取商品列表失败:", err);
        uni.showToast({
          title: "获取商品列表失败",
          icon: "none",
        });
      }
    },

    // 处理搜索输入
    handleSearch() {
      if (!this.searchKeyword) {
        this.filteredProducts = this.brandProducts;
        return;
      }
      
      const keyword = this.searchKeyword.toLowerCase();
      this.filteredProducts = this.brandProducts.filter(product => 
        product.name.toLowerCase().includes(keyword)
      );
    },

    // 添加初始化第一个标签的方法
    initializeFirstTag() {
      if (this.currentBrands.length > 0) {
        this.selectedTags = [this.currentBrands[0].code];
      }
    },

    goToDetail(item) {
      uni.navigateTo({
        url: `/preferredPages/productDetail?id=${item.id}`
      });
    },

    // 添加 goBack 方法
    goBack() {
      uni.navigateBack();
    },

    // 获取分类列表
    async fetchCategories() {
      try {
        const res = await this.$minApi.getCategoriesList();
        console.log(res,111);
        
        if (res.success) {
          this.tabbar = res.data
          // 如果有分类数据，默认获取第一个分类的品牌
          if (this.tabbar.length > 0) {
            await this.fetchBrandsByCategory(this.tabbar[0].id);
          }
        }
      } catch (err) {
        console.error("获取分类列表失败:", err);
        uni.showToast({
          title: "获取分类列表失败",
          icon: "none",
        });
      }
    },
  },
};
</script>



<style lang="scss" scoped>
.tn-tabbar-height {
  min-height: 120rpx;

  height: calc(140rpx + env(safe-area-inset-bottom) / 2);
}

/* 胶囊*/

.tn-custom-nav-bar__back {
  width: 100%;

  height: 100%;

  position: relative;

  display: flex;

  justify-content: space-evenly;

  align-items: center;

  box-sizing: border-box;

  background-color: rgba(0, 0, 0, 0.15);

  border-radius: 1000rpx;

  border: 1rpx solid rgba(255, 255, 255, 0.5);

  color: #ffffff;

  font-size: 18px;

  .icon {
    display: block;

    flex: 1;

    margin: auto;

    text-align: center;
  }

  &:before {
    content: " ";

    width: 1rpx;

    height: 110%;

    position: absolute;

    top: 22.5%;

    left: 0;

    right: 0;

    margin: auto;

    transform: scale(0.5);

    transform-origin: 0 0;

    pointer-events: none;

    box-sizing: border-box;

    opacity: 0.7;

    background-color: #ffffff;
  }
}

.tn-classify {
  min-height: 100vh;
  background: #f7f8fa;

  &__search {
    &--wrap {
      padding: 20rpx 24rpx;
      background: #fff;
      border-bottom: 1px solid rgba(24, 144, 255, 0.1);
    }

    &__box {
      width: 100%;
      height: 70rpx;
      border-radius: 35rpx;
      background: #f1f6ff !important;
      padding: 0 30rpx;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
      }
    }

    &__icon {
      margin-right: 10rpx;
      color: #1890ff;
    }

    &__text {
      font-size: 28rpx;
      color: #999;
    }
  }

  &__container {
    background: #fff !important;

    &__wrap {
      border-radius: 16rpx 16rpx 0 0;
      overflow: hidden;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    }
  }

  &__left-box {
    background: #f1f6ff;
    border-right: 1px solid rgba(24, 144, 255, 0.1);
    width: 180rpx;
    flex: none !important;
  }

  &__tabbar {
    &__item {
      height: 100rpx;
      position: relative;
      transition: all 0.3s ease;

      &__title {
        font-size: 28rpx;
        color: #666;
        padding: 0 30rpx;
        text-align: center;
        line-height: 1.5;
      }

      &--active {
        background: #fff;
        color: #1890ff;
        font-weight: 500;

        .tn-classify__tabbar__item__title {
          color: #1890ff;
        }

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 6rpx;
          height: 36rpx;
          background: #1890ff;
          border-radius: 0 3rpx 3rpx 0;
        }
      }

    }
  }
}

.brand-tags {
  padding: 16rpx;
  background: #fff;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

  &__header {
    margin-bottom: 12rpx;
    padding-bottom: 12rpx;
    border-bottom: 1px solid rgba(24, 144, 255, 0.1);

    text {
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
    }

    .select-all {
      font-size: 24rpx;
      color: #1890ff;
      cursor: pointer;
    }
  }

  &__content {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
  }

  .brand-tag {
    padding: 6rpx 16rpx;
    background: #f1f6ff;
    border-radius: 24rpx;
    font-size: 24rpx;
    color: #666;
    transition: all 0.3s ease;
    border: 1px solid rgba(24, 144, 255, 0.1);

    &--active {
      background: #1890ff;
      color: #fff;
      border-color: #1890ff;
    }
  }
}

.goods-list {
  padding: 0 20rpx;

  .goods-item {
    background: #fff;
    border-radius: 12rpx;
    padding: 16rpx;
    margin-bottom: 12rpx;
    display: flex;
    flex-direction: column;
    
    .row-1 {
      display: flex;
      margin-bottom: 12rpx;

      .goods-image {
        width: 70rpx;
        height: 70rpx;
        border-radius: 8rpx;
        margin-right: 16rpx;
        background: #f1f6ff;
        flex-shrink: 0;
      }
      
      .title-container {
        flex: 1;
        min-width: 0;
        padding-top: 2rpx;
        display: flex;
        flex-direction: column;
        width: 0;
        
        .goods-title {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 6rpx;
          line-height: 1.4;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .goods-spec {
          font-size: 24rpx;
          color: #999;
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
    
    .price-info {
      background: rgba(24, 144, 255, 0.04);
      border-radius: 8rpx;
      padding: 8rpx 12rpx;
      
      .row-2 {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
        margin-bottom: 4rpx;
        background: none;
        padding: 0;
      }
      
      .row-3 {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
        background: none;
        padding: 0;
      }
      
      .price {
        font-size: 26rpx;
        color: #333;
        font-weight: 500;
        
        &::before {
          content: '¥';
          font-size: 22rpx;
          margin-right: 1rpx;
        }
        
        &:nth-child(3) {
          color: #ff4d4f;
        }
      }
      
      .price-desc {
        font-size: 22rpx;
        color: #666;
        white-space: nowrap;
        
        &:nth-child(3) {
          color: #ff4d4f;
        }
      }
    }
  }
}

.tag {
  display: inline-block;
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
  font-size: 20rpx;
  margin-right: 6rpx;
  line-height: 1.2;
  
  &--hot {
    color: #fff;
    background: #ff4d4f;
  }
  
  &--return {
    color: #1890ff;
    background: rgba(24, 144, 255, 0.1);
  }
}

.row-1 {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 8px;
  // padding-bottom: 6px;
  border-bottom: 1px solid #f0f0f0;
}

.goods-image {
  width: 30px;
  height: 30px;
  object-fit: cover;
  border-radius: 6px;
  cursor: pointer;
  flex-shrink: 0;
}

.title-container {
  flex: 1;
  min-width: 0;
  padding-top: 2rpx;
  display: flex;
  flex-direction: column;
  width: 0;
  
  .goods-title {
    font-size: 26rpx;
    color: #333;
    margin-bottom: 6rpx;
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  
  .goods-spec {
    font-size: 22rpx;
    color: #999;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.row-2 {
  display: flex;
  justify-content: space-between;
  padding: 2rpx 8rpx;
  background: #f1f6ff;
  border-radius: 4rpx;
  // margin-bottom: 2rpx;
  
  &:last-of-type {
    margin-bottom: 0;
    background: #f0f7ff;
  }
}

.row-3 {
  display: flex;
  justify-content: space-between;
  padding: 2rpx 8rpx;
  background: #f1f6ff;
  border-radius: 4rpx;
}

.price {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  
  &::before {
    content: '¥';
    font-size: 22rpx;
    margin-right: 1rpx;
  }
  
  &:nth-child(3) {
    color: #ff4d4f;
  }
}

.price-desc {
  font-size: 22rpx;
  color: #666;
  white-space: nowrap;

  &:nth-child(3) {
    color: #ff4d4f;
  }
}

.price-row {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.quantity-tag {
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  background: #e6f7ff;
  color: #1890ff;
  border-radius: 2rpx;
  white-space: nowrap;
  
  &.two-pieces {
    background: #fff1f0;
    color: #ff4d4f;
  }
}

.price-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
  margin-left: 4rpx;
  
  .price {
    width: 33.33%;
    text-align: center;
    
    &:first-child {
      text-align: left;
    }
    
    &:last-child {
      text-align: right;
    }
  }
}

// 添加导航栏样式

.tn-custom-nav-bar__back {
  width: 100%;

  height: 100%;

  display: flex;

  align-items: center;

  .icon {
    font-size: 40rpx;

    margin-right: 10rpx;
  }
}

.tn-classify__search {
  &__input {
    flex: 1;
    height: 70rpx;
    font-size: 28rpx;
    color: #333;
    padding: 0 10rpx;
  }
}

.price-info-container {
  background: #f1f6ff;
  border-radius: 8rpx;
  padding: 8rpx;
  margin-top: 8rpx;

  .row-2 {
    background: transparent;
    padding: 4rpx 6rpx;
    margin-bottom: 4rpx;
    
    &:last-of-type {
      margin-bottom: 4rpx;
      background: rgba(255, 77, 79, 0.04);
    }
  }

  .row-3 {
    background: transparent;
    padding: 4rpx 6rpx;
    border-top: 1px solid rgba(0,0,0,0.05);
  }
}

.category-scroll {
  width: 100%;
  background: #fff;
  border-bottom: 1px solid rgba(24, 144, 255, 0.1);
  
  .category-list {
    display: flex;
    white-space: nowrap;
    padding: 0 20rpx;
    
    .category-item {
      display: inline-block;
      padding: 24rpx 32rpx;
      font-size: 28rpx;
      color: #666;
      position: relative;
      
      &--active {
        color: #1890ff;
        font-weight: 500;
        
        &::after {
          content: '';
          position: absolute;
          left: 50%;
          bottom: 0;
          transform: translateX(-50%);
          width: 40rpx;
          height: 4rpx;
          background: #1890ff;
          border-radius: 2rpx;
        }
      }
    }
  }
}

// 修改左侧品牌容器样式
.tn-classify__left-box {
  background: #f1f6ff;
  border-right: 1px solid rgba(24, 144, 255, 0.1);
  width: 180rpx;
  flex: none !important;
}
</style>


